package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmMaterialDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.WmMaterial;
import com.heima.model.common.pojos.WmNewsMaterial;
import com.heima.model.common.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    //将文件上传工具注入
    @Autowired
    FastDFSClient  fastDFSClient;
    //将文件前缀注入
    @Value("${fdfs.url}")
    private  String fileServerUrl;


    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //判断参数
        if(multipartFile==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        String fileId=null;
        try {
            //上传文件
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将图片保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        //从线程中获取当前用户
        WmUser user = WmThreadLocalUtils.getUser();
        //给图片信息赋值
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        //保存图片
        save(wmMaterial);
        //拼接图片的路径=注入的图片地址:fileServerUrl+上传图片获取的：fileId
        //返回给前端显示
        String picterUrl =fileServerUrl+fileId;
        wmMaterial.setUrl(picterUrl);

        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
       //判断分页
        dto.checkParam();

        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //当前用户查询自己的图片信息
        lambdaQueryWrapper.eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId());
        //判断用户是否收藏
        if(dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //根据创建时间进行排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //查询
        IPage result = page(page, lambdaQueryWrapper);

        //封装结果
        ResponseResult responseResult =new PageResponseResult(dto.getPage(),dto.getSize(), (int) result.getTotal());
        //给图片加前缀，不然前端无法显示
        List<WmMaterial> datas = result.getRecords();
        for (WmMaterial data : datas) {
            data.setUrl(fileServerUrl+data.getUrl());
        }
        responseResult.setData(datas);

        return responseResult;
    }

    @Autowired
    WmNewsMaterialMapper  wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //先判断参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询是否有对应图片存在，并获得图片信息
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //根据图片信息的ID查询中间表判断是否关联
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery()
                                                      .eq(WmNewsMaterial::getMaterialId, id));

        if(count>0){
            //图片被引用不能被删除
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"当前图片被引用，无法删除");
        }
        //删除FastDFS中的图片
        fastDFSClient.delFile(wmMaterial.getUrl());
        //删除数据库中的数据
        removeById(id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    //修改收藏状态
    @Override
    public ResponseResult updateCollection(Integer id, Short type) {
        //判断参数
        if(id==null||type==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //修改数据库收藏状态
        update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId())
                .set(WmMaterial::getIsCollection,type));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
